package com.ezlcp.gateway.filter;

import com.ezlcp.commons.constant.Constants;
import com.ezlcp.commons.tool.StringUtils;
import com.ezlcp.commons.utils.RequestUtil;
import com.ezlcp.gateway.config.NoTokenException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @Author: szw
 * @Description: 自定义忽略url但必须带上token网关全局过滤器
 * @Date: Created in 2020/10/13.
 */
@Slf4j
@Component
public class TokenRequestFilter implements GlobalFilter, Ordered {

    @Value("#{'${ezlcp.ignore.auth.urls}'.trim().split(',')}")
    private List<String> ignoreUrls;

    /**
     * @return get请求参考spring cloud gateway自带过滤器：
     * @see org.springframework.cloud.gateway.filter.factory.AddRequestParameterGatewayFilterFactory
     * post请求参考spring cloud gateway自带过滤器：
     * @see org.springframework.cloud.gateway.filter.factory.rewrite.ModifyRequestBodyGatewayFilterFactory
     */
    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.debug("----自定义忽略url但必须带上token网关全局过滤器生效----");
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        //当前URL是否配置在忽略验证名单中
        String reqUrl = serverHttpRequest.getPath().value();
        if (RequestUtil.containsUrl(reqUrl, ignoreUrls)) {
            return chain.filter(exchange);
        }
        MultiValueMap<String, String> headers = serverHttpRequest.getHeaders();
        String token = headers.getFirst(Constants.TOKEN);
        if (StringUtils.isEmpty(token)) {
            token = headers.getFirst(Constants.Authorization);
        }
        if (StringUtils.isEmpty(token)) {
            var params = serverHttpRequest.getQueryParams();
            if (params != null) {
                token = params.getFirst(Constants.TOKEN);
            }
        }
        if (StringUtils.isEmpty(token)) {
            log.error("---TokenRequestFilter.filter is error : token is null");
            throw new NoTokenException("token.noTokenParam");
        }
        //暂时不验证Token的有效性，因为要配置redis才可以
//        var loginUser = TokenUtil.getUserByToken(token);
//        if (loginUser == null) {
//            log.error("---HttpTokenRequestFilter.filter is error : token is invalid !");
//            throw new IllegalStateException("Invalid URI query: token is invalid !");
//        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 99;
    }


}
